package pachet.doi;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Bluetooth extends ListActivity {
	
	private static final int REQUEST_ENABLE_BT = 10;
	private Collection<String> devices;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  setListAdapter(new ArrayAdapter<String>(this, R.layout.item, new String[] {}));

	  BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
	  if (ba != null) {
		  if (!ba.isEnabled()) {
			  Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			  startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
		  } else {
			 showDeviceList();
		  }
	  }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_ENABLE_BT)
			if (resultCode == RESULT_OK) {
				showDeviceList();
			}
	}

	private void showDeviceList() {
		devices = new ArrayList<String>();
		
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
		if (pairedDevices.size() > 0) {
			for (BluetoothDevice device : pairedDevices)
				devices.add(device.getName());
		}
		
		final BroadcastReceiver receiver = new BroadcastReceiver() {
			
			public void onReceive(Context arg0, Intent arg1) {
				String action = arg1.getAction();
				repaintDevList();
				if (BluetoothDevice.ACTION_FOUND.equals(action)) {
					BluetoothDevice device = arg1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					devices.add(device.getName());
					repaintDevList();
				}
				
			}
		};
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(receiver, filter);
		
		repaintDevList();
		adapter.startDiscovery();
	}
	
	

	private void repaintDevList() {
		setListAdapter(new ArrayAdapter<String>(this, R.layout.item, devices.toArray(new String[0])));

		  ListView lv = getListView();
		  lv.setTextFilterEnabled(true);

		  lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		      // When clicked, show a toast with the TextView text
		      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
		          Toast.LENGTH_SHORT).show();
		    }
		  });
		
	}
	
}
